import React, { useEffect, useState } from 'react';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import { message } from 'antd';
import { uploadFile } from '@/services/FileService';
import '@wangeditor/editor/dist/css/style.css';
import styles from './index.less';

interface RichTextEditorProps {
  value?: string;
  onChange?: (html: string) => void;
  height?: number;
}

const RichTextEditor: React.FC<RichTextEditorProps> = ({
  value,
  onChange,
  height = 500
}) => {
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null);
  // 编辑器内容
  const [html, setHtml] = useState<string>(value || '');

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {
    excludeKeys: []
  };

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {
        customUpload: async (file: File, insertFn: any) => {
          try {
            const fileId = await uploadFile(file);
            insertFn(`/api/file/play/${fileId}`);
          } catch (error) {
            message.error('图片上传失败');
          }
        }
      }
    }
  };

  // 及时销毁 editor
  useEffect(() => {
    return () => {
      if (editor === null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  // 初始化值
  useEffect(() => {
    if (value !== undefined) {
      setHtml(value);
    }
  }, [value]);

  return (
    <div className={styles.editor} style={{ border: '1px solid #ccc', zIndex: 100 }}>
      <Toolbar
        editor={editor}
        defaultConfig={toolbarConfig}
        mode="default"
        style={{ borderBottom: '1px solid #ccc' }}
      />
      <Editor
        defaultConfig={editorConfig}
        value={html}
        onCreated={setEditor}
        onChange={editor => {
          setHtml(editor.getHtml());
          onChange?.(editor.getHtml());
        }}
        mode="default"
        style={{ height: `${height}px`, overflowY: 'hidden' }}
      />
    </div>
  );
};

export default RichTextEditor; 